package javaSenior.threadExer;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-02 23:37
 * @description 使用同步机制将单例模式中的懒汉式改写为线程安全的
 */
public class BankLazyTest {
}

class Bank{
    private Bank(){}

    private static Bank instance=null;
    //此时的锁是Bank.class，此时便是线程安全的

    public static synchronized Bank getInstance() {
        if (instance == null) {
            instance = new Bank();
        }
        return instance;
    }

    public static Bank getInstance2() {
        //方式1：效率稍差
//        synchronized (Bank.class) {
//            if (instance == null) {
//                instance = new Bank();
//            }
//            return instance;
//        }
        //方式2：加一层判断，效率更高
        if(instance==null){
            synchronized (Bank.class) {
            if (instance == null) {
                instance = new Bank();
            }
            return instance;
        }
        }
        return instance;
    }

}